package com.guguskins.back.common.helper;

import com.guguskins.back.entity.GuPermission;


import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 根据权限数据构建菜单数据
 * </p>
 *
 * @author qy
 * @since 2019-11-11
 */
public class PermissionHelper {

    /**
     * 使用递归方法建菜单
     *
     * @param treeNodes
     * @return
     */
    public static List<GuPermission> build(List<GuPermission> treeNodes) {
        List<GuPermission> trees = new ArrayList<>();
        for (GuPermission treeNode : treeNodes) {
            if (treeNode.getPid().equals(0)) {
                treeNode.setLevel(1);
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     *
     * @param treeNode
     * @param treeNodes
     * @return
     */
    public static GuPermission findChildren(GuPermission treeNode, List<GuPermission> treeNodes) {
        treeNode.setChildren(new ArrayList<>());

        for (GuPermission it : treeNodes) {
            if (treeNode.getId().equals(it.getPid())) {
                int level = treeNode.getLevel() + 1;
                it.setLevel(level);
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }
}
